﻿using Engine.Particles.Interfaces;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Engine.Particles.Effects
{
    public class Particle : ParticleBase
    {
        private SpriteBatch _spriteBatch;
        public Texture2D Texture { get; set; }
        public Vector2 Position { get; set; }
        public Vector2 Acceleration { get; set; }
        public Vector2 Velocity { get; set; }
        public float Angle { get; set; }
        public float AngularVelocity { get; set; }
        public Color Color { get; set; }
        public float Size { get; set; }
        public int TimeToLive { get; set; }
        public bool UseGravity { get; set; }
        public Vector2 Gravity { get; set; }
        public Vector2 PseudoGravity { get; private set; }

        public static Particle Create(Texture2D texture, Vector2 position, Vector2 velocity, float angle, float angularVelocity, Color color, float size, int timeToLive, Vector2 gravity, Vector2 acceleration, bool useGravity = false )
        {
            var pseudoGravity = new Vector2(0,.98f);

            if (!useGravity)
            {
                gravity = new Vector2(1, 1);
                acceleration = new Vector2(1, 1);
                pseudoGravity = Vector2.Zero;
            }

            return new Particle()
                       {
                           Texture = texture,
                           Position = position,
                           Velocity = velocity,
                           Angle = angle,
                           AngularVelocity = angularVelocity,
                           Color = color,
                           Size = size,
                           TimeToLive = timeToLive,
                           Gravity = gravity,
                           Acceleration = acceleration,
                           PseudoGravity = pseudoGravity
                       };
        }

        public virtual void Update(GameTime gameTime)
        {
            Acceleration = Acceleration * Gravity;
            TimeToLive--;
            Position += Velocity * Acceleration + PseudoGravity;
            Angle += AngularVelocity * Acceleration.Y;
        }

        public override void Draw(GameTime gameTime){
            var sourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height);
            var origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
            _spriteBatch.Draw(Texture, Position, sourceRectangle, Color, Angle, origin, Size, SpriteEffects.None, 0f);
        }

        public override void SetSpriteBatch(SpriteBatch spriteBatch){
            if (_spriteBatch == null)
                _spriteBatch = spriteBatch;
        }
    }
}
